from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, SelectField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Optional
from flask_login import current_user
from flask_blog.models import User

class RegistrationForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
                                     validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Sign Up')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user:
            raise ValidationError('That username is taken. Please choose a different one.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user:
            raise ValidationError('That email is taken. Please choose a different one.')

class LoginForm(FlaskForm):
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')

class UpdateAccountForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpg', 'png'])])
    submit = SubmitField('Update')

    def validate_username(self, username):
        if username.data != current_user.username:
            user = User.query.filter_by(username=username.data).first()
            if user:
                raise ValidationError('That username is taken. Please choose a different one.')

    def validate_email(self, email):
        if email.data != current_user.email:
            user = User.query.filter_by(email=email.data).first()
            if user:
                raise ValidationError('That email is taken. Please choose a different one.')

class PostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    # 手动输入内容（可选，若上传文件则优先用文件内容）
    content = TextAreaField('Content (optional)', validators=[Optional()])
    # 格式选择下拉框
    content_format = SelectField(
        'Content Format',
        validators=[DataRequired()],
        choices=[
            ('txt', 'Plain Text (TXT)'),
            ('markdown', 'Markdown (MD)'),
            ('docx', 'Word Document (DOCX)')
        ]
    )
    # 文件上传（可选，支持 txt/md/docx）
    content_file = FileField(
        'Upload File (optional)',
        validators=[
            Optional(),
            FileAllowed(['txt', 'md', 'docx'], 'Only TXT/MD/DOCX files are allowed!')
        ]
    )
    submit = SubmitField('Post')

    # 自定义验证：要么输入内容，要么上传文件
    def validate(self, extra_validators=None): 
        if not super().validate(extra_validators=extra_validators):
            return False
        # 若未上传文件且未输入内容，报错
        if not self.content_file.data and not self.content.data.strip():
            self.content.errors.append('Either enter content or upload a file!')
            return False
        # 若上传文件，自动同步格式（根据文件后缀）
        if self.content_file.data:
            filename = self.content_file.data.filename
            if filename.endswith('.txt'):
                self.content_format.data = 'txt'
            elif filename.endswith('.md'):
                self.content_format.data = 'markdown'
            elif filename.endswith('.docx'):
                self.content_format.data = 'docx'
        return True

class RequestResetForm(FlaskForm):
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    submit = SubmitField('Request Password Reset')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is None:
            raise ValidationError('There is no account with that email. You must register first.')

class ResetPasswordForm(FlaskForm):
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
                                     validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Reset Password')
